import React from 'react';
import { Form, Input, Select, Textarea, Dialog } from 'tdesign-react';
import { FormProps } from 'tdesign-react';
import { JupiterUrlResource } from '../../../types/urlResourceTypes';
import DictionarySelect from '../../../components/Dictionary/DictionarySelect';

const { FormItem } = Form;
const { Option } = Select;

interface Props {
  visible: boolean;
  onClose: () => void;
  onSubmit: (data: Partial<JupiterUrlResource>) => void;
  initialData?: Partial<JupiterUrlResource>;
  title: string;
}

export default function UrlResourceForm({
  visible,
  onClose,
  onSubmit,
  initialData = {},
  title,
}: Props) {
  const [form] = Form.useForm();

  const handleSubmit: FormProps['onSubmit'] = ({ validateResult, fields }) => {
    if (validateResult === true) {
      onSubmit(fields as Partial<JupiterUrlResource>);
    }
  };

  return (
    <Dialog
      closeOnOverlayClick={false}
      header={title}
      visible={visible}
      onClose={onClose}
      onConfirm={() => form.submit()}
      destroyOnClose
      width={600}
    >
      <Form
        form={form}
        initialData={initialData}
        layout="vertical"
        onSubmit={handleSubmit}
      >
        <FormItem
          label="URL路径"
          name="url"
          rules={[{ required: true, message: '请输入URL路径' }]}
        >
          <Input placeholder="请输入URL路径，如：/api/users" />
        </FormItem>

        <FormItem
          label="请求方法"
          name="method"
          rules={[{ required: true, message: '请选择请求方法' }]}
          initialData={initialData?.method || "GET"}
        >
          <DictionarySelect
            dictType="http_method"
            placeholder="请选择请求方法"
          />
        </FormItem>

        <FormItem
          label="所属模块"
          name="module"
          initialData={initialData?.module || ""}
        >
          <DictionarySelect
            dictType="module"
            placeholder="请选择所属模块"
            clearable={true}
          />
        </FormItem>

        <FormItem
          label="描述"
          name="description"
        >
          <Textarea placeholder="请输入URL描述" rows={3} />
        </FormItem>
      </Form>
    </Dialog>
  );
}